#include <iostream>
#include <string>
#include <winsock.h>
#include <cstring>
using namespace std;

//链接静态库
#pragma comment (lib,"ws2_32.lib")

static string serverip = "43.139.37.242";
static uint16_t serverport = 3389;

int main()
{
	WSADATA wsaData;
	//启动Winsock
	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)           // 初始化Winsock库
	{
		cerr << "WSAStartup() error!" << endl;
	}
	else
	{
		cout << "WSAStartup() success" << endl;
	}
	SOCKET sock;
	sock = socket(AF_INET, SOCK_DGRAM, 0); //UDP
	if (sock == -1)
	{
		cerr << "socket fail" << endl;
	}
	else cout << "socket success" << endl;
	//填写server信息
	struct sockaddr_in server;
	memset(&server, 0, sizeof(server));
	server.sin_addr.s_addr = inet_addr(serverip.c_str());
	server.sin_family = AF_INET;
	server.sin_port = htons(serverport);
	while (true)
	{
		//开始向服务器发送信息
		cout << "Enter# " << endl;
		string message;
		getline(cin, message);
		int s = sendto(sock, message.c_str(),message.size(), 0, (struct sockaddr*)&server, sizeof(server));
		if (s < 0)
		{
			cerr << "send to error" << endl;
			break;
		}
		//接受服务器送来的信息
		char buffer[1024];
		buffer[0] = 0; // C式清空
		struct sockaddr_in peer;
		int len = sizeof(peer);
		int n = recvfrom(sock, buffer, len, 0, (struct sockaddr*)&peer, &len);
		if (n > 0)
		{
			buffer[n] = 0;
			cout << "server[echo] # " << buffer << endl;
		}
		else break;
	}
	return 0;
}